<?php
/**
 * PHPECS社交电商系统，使用thinkphp框架+MySQL数据库编写的小程序商城系统，基于LGPL协议开源授权
 * @package phpecs
 * @author qq(123865789)
 * @copyright 2018-2020 深圳塔灯网络科技有限公司
 * @version 2.0
 * @license http://www.phpecs.com/lgpl.html phpecs开源授权协议：GNU Lesser General Public License
 **/
namespace app\admin\model\store;
use app\admin\model\market\MarketSpell;
use app\admin\model\user\User;
use app\admin\model\user\UserCash;
use app\admin\model\user\UserGold;
use app\admin\model\user\UserRecord;
use think\Model;
class StoreOrder extends Model{

    /**
     * 统计条数
     * @param $where
     * @return int|string
     * @throws \think\Exception
     */
    public static function countOrder($where){
        return self::where($where)->count();
    }

    /**
     * 活动条件统计
     * @param $where
     * @param $status
     * @return int|string
     */
    public static function countOrderDuo($where, $status){
        return self::where($where)->where('active_status', $status)->count();
    }

    /**
     * 分页输出
     * @param $where
     * @param $paginate
     * @param string $order
     * @return $this
     */
    public static function selOrderPage($where, $paginate, $order = 'time desc'){
        return self::where($where)->order($order)->paginate($paginate)->each(function ($item, $k){
            if ($item['type'] == 3 && $item['status'] != 0){ //拼团订单
                //查出订单所属活动
                $market = MarketSpell::getSpellInfo(['id' => $item['spell_id']], 'id, pid, spell_number, spell_time, status');
                $product = StoreProduct::getProductInfo(['id' => $market['pid']], ''); //商品
                $count = StoreOrder::countOrder(['spell_id' => $market['id'], 'status' => ['neq', 0], 'spell_number' => $item['spell_number']]);
                if (!$market || $market['status'] != 1 || !$product || $product['status'] != 0 || $product['is_del'] != 0) {
                    $msg = '已结束';
                    $color = '#52503f';
                }elseif (time() > ($item['time'] + $market['spell_time']) && $count < $market['spell_number']){
                    $msg = '未完成';
                    $color = '#e25b45';
                }elseif ($count < $market['spell_number']){
                    $msg = '进行中';
                    $color = '#457856';
                }elseif ($count == $market['spell_number']){
                    $msg = '已完成';
                    $color = '#3c54ff';
                }
                $item['msg'] = $msg;
                $item['color'] = $color;
            }
            //查询出订单详情
            $field = 'o.spec,o.num,p.id,p.name';
            $details = StoreOrderList::selOrderListZhi($item['id'], $field);
            foreach ($details as $key => $val){
                $details[$key]['img'] = StoreProductImg::getField(['pid' => $val['id']], 'img');
            }
            $item['lower'] = $details;
            return $item;
        });
    }

    /**
     * 查询一条数据
     * @param $where
     * @param string $field
     * @return array|false|\PDOStatement|string|Model
     */
    public static function getOrderInfo($where, $field = ''){
        return self::where($where)->field($field)->find();
    }

    /**
     * 修改某一个字段
     * @param $where
     * @param $field
     * @param $value
     * @return int
     */
    public static function upField($where, $field, $value){
        return self::where($where)->setField($field, $value);
    }

    /**
     * 获取一个字段的值
     * @param string $where
     * @param null $value
     * @return mixed
     */
    public static function getField($where, $value, $type = 0){
        if ($type == 0){
            return self::where($where)->value($value);
        }else{
            return self::where($where)->column($value);
        }
    }

    /**
     * 修改订单数据
     * @param $where
     * @param $data
     * @return int
     */
    public static function edit($where, $data){
        return self::where($where)->update($data);
    }

    /**
     * 条数查询
     * @param $where
     * @param $page
     * @param $limit
     * @param string $order
     */
    public static function selOrderLimit($where, $page, $limit, $order = 'time desc'){
        $data = self::where($where)->order($order)->limit($page, $limit)->select();
        $count = self::where($where)->count();
        $list = [
            'data' => $data,
            'count' => $count
        ];
        return $list;
    }

    /**
     * 活动条数查询
     * @param $where
     * @param $page
     * @param $limit
     * @param string $order
     */
    public static function selSpellOrderLimit($where, $page, $limit, $order = 'o.time desc'){
        $field = 'o.id, o.spell_number, o.time start_time, s.name, s.spell_number num, s.spell_time, s.status spell_status
        , u.name username, p.status product_status, p.is_del';
        $data = self::alias('o')->join('market_spell s', 'o.spell_id = s.id', 'left')->join('user u', 'o.uid = u.id')->join('store_product p', 's.pid = p.id', 'left')
            ->where($where)->where('o.order = o.spell_number')->field($field)->order($order)->limit($page, $limit)->select();
        foreach ($data as $k => $v){
            $count = self::countOrder(['spell_number' => $v['spell_number'], 'status' => 1]);
            $end_time = $v['start_time'] + $v['spell_time'];
            $data[$k]['username'] = base64_decode($v['username']);
            $data[$k]['count'] = $count;
            $data[$k]['end_time'] = $end_time;
            //活动结束
            if ($v['spell_status'] === '' || $v['spell_status'] == 0 || $v['product_status'] === '' || $v['product_status'] == 1 || $v['is_del'] == 1){
                $data[$k]['status'] = '活动已结束或已下架';
            }elseif (time() > $end_time && $count < $v['num']){
                $data[$k]['status'] = '活动已结束或已下架';
            }elseif ($count == $v['num']){ //已完成
                $data[$k]['status'] = '已完成';
            }elseif ($count <= $v['num']){ //进行中
                $data[$k]['status'] = '进行中';
            }
        }
        $count = self::alias('o')->join('market_spell s', 'o.spell_id = s.id')->join('user u', 'o.uid = u.id')->join('store_product p', 's.pid = p.id', 'left')
            ->where($where)->where('o.order = o.spell_number')->count();
        return compact('data', 'count');
    }

    /**
     * 查询订单数据
     * @param $where
     */
    public static function selOrderNum($where){
        $data = self::where($where)->where('status', 'neq', 0)->field('id, time')->select();
        foreach ($data as $k => $v){
            $data[$k]['num'] = StoreOrderList::sumOrderList(['oid' => $v['id']], 'num');
        }
        return $data;
    }

    /**
     * 返回ECharts查询数据
     * @param $status
     * @param string $order
     * @return array
     */
    public static function selOrderECharts($orderStatus, $status, $dateTime, $order = 'time asc'){
        if ($orderStatus) $orderWhere['status'] = $orderStatus - 1;
        $min = self::where($orderWhere)->min('time');
        $minTime = $min ? strtotime(date('Y-m-d', $min)) : time(); //数据库里面最小的时间
        if ($status == 5){
            $dateTime = explode(' - ', $dateTime);
            $start = strtotime($dateTime[0]) < $minTime ? $minTime : strtotime($dateTime[0]);
            $end = strtotime($dateTime[1]) + 86399; //结束时间是日期按当天最后一秒算
            $where['time'] = [['egt', $start], ['elt', $end]];
            $day = ceil((($end - $start) / 86400)); //计算有多少天
        }else{
            $start = TimeAssign($status); //开始时间
            if ($start) {
                $where['time'] = ['egt', $start];
                //如果小于数据库最小时间直接使用数据库最小时间开始组合
                $start = $start < $minTime ? $minTime : $start;
            }else{
                $start = $minTime;
            }
            $day = ceil(((time() - $start) / 86400)); //计算有多少天
        }
        $data = self::where($orderWhere)->where($where)->field('id, time, money, benefit')->order($order)->select();
        $count['turnover'] = self::sum('money-benefit'); //总营业额
        $count['benefit'] = self::sum('benefit'); //优惠金额
        $count['orderNum'] = self::count(); //订单数量
        $count['shopNum'] = StoreOrderList::sumOrderList('', 'num'); //订单商品数量
        $count['turnoverWhere'] = 0; //指定条件的营业额
        $count['benefitWhere'] = 0; //指定条件的优惠金额
        $count['orderNumWhere'] = count($data); //指定条件的订单数量
        $count['shopNumWhere'] = 0; //指定条件的订单商品数量
        foreach ($data as $k => $v){
            $data[$k]['num'] = StoreOrderList::sumOrderList(['oid' => $v['id']], 'num');
            $data[$k]['refundMoney'] = StoreRefund::getField(['oid' => $v['id']], 'tui');
            $count['turnoverWhere'] += $v['money'] - $v['benefit'];
            $count['benefitWhere'] += $v['benefit'];
            $count['shopNumWhere'] += $data[$k]['num'];
        }
        $arr = []; //新的数组
        for ($i = 0; $i < $day; $i++){
            $startTime = $start + 86400 * $i; //每天开始时间戳
            $endTime = $start + 86400 * $i + 86400; //每天结束时间戳
            $daily = date('Y-m-d', $startTime); //每天的日期
            $arr[$daily]['orderNum'] = 0; //订单数量
            $arr[$daily]['shopNum'] = 0; //商品数量
            $arr[$daily]['orderMoney'] = 0; //订单金额
            $arr[$daily]['refundMoney'] = 0; //退款金额
            foreach ($data as $k => $v){
                if ($v['time'] >= $startTime && $v['time'] < $endTime){
                    $arr[$daily]['orderNum'] += 1;
                    $arr[$daily]['shopNum'] += $v['num'];
                    $arr[$daily]['orderMoney'] += $v['money'];
                    $arr[$daily]['refundMoney'] += $v['refundMoney'];
                }
            }
        }
        return compact('arr', 'count');
    }

    /**
     * 返回财务报表
     * @param $status
     * @param string $order
     * @return array
     */
    public static function selOrderECharts2($status, $dateTime, $order = 'time asc'){
        $min = self::where('status', 'neq', 0)->min('time');
        $minTime = $min ? strtotime(date('Y-m-d', $min)) : time(); //数据库里面最小的时间
        if ($status == 5){
            $dateTime = explode(' - ', $dateTime);
            $start = strtotime($dateTime[0]) < $minTime ? $minTime : strtotime($dateTime[0]);
            $end = strtotime($dateTime[1]) + 86399; //结束时间是日期按当天最后一秒算
            $where['time'] = [['egt', $start], ['elt', $end]];
            $day = ceil((($end - $start) / 86400)); //计算有多少天
        }else{
            $start = TimeAssign($status); //开始时间
            if ($start) {
                $where['time'] = ['egt', $start];
                //如果小于数据库最小时间直接使用数据库最小时间开始组合
                $start = $start < $minTime ? $minTime : $start;
            }else{
                $start = $minTime;
            }
            $day = ceil(((time() - $start) / 86400)); //计算有多少天
        }
        $data = self::where('status', 'neq', 0)->where($where)->field('id, time, money, benefit')->order($order)->select();
        $where2 = $where ? array_merge($where, ['status' => 1]) : ['status' => 1]; //合并时间条件
        $data2 = UserRecord::selRecord($where2, 'time, money'); //充值数据
        $data3 = UserCash::selCash($where2, 'time, money'); //提现数据
        $data4 = UserGold::selGold($where, 'time, gold'); //佣金数据
        $arr = []; //新的数组
        for ($i = 0; $i < $day; $i++){
            $startTime = $start + 86400 * $i; //每天开始时间戳
            $endTime = $start + 86400 * $i + 86400; //每天结束时间戳
            $daily = date('Y-m-d', $startTime); //每天的日期
            $arr[$daily]['whole'] = 0; //营业额
            $arr[$daily]['expend'] = 0; //支出
            foreach ($data as $k => $v){
                if ($v['time'] >= $startTime && $v['time'] < $endTime){
                    $arr[$daily]['whole'] += ($v['money'] - $v['benefit']);
                }
            }
            foreach ($data2 as $k => $v){
                if ($v['time'] >= $startTime && $v['time'] < $endTime){
                    $arr[$daily]['whole'] += $v['money'];
                }
            }
            foreach ($data3 as $k => $v){
                if ($v['time'] >= $startTime && $v['time'] < $endTime){
                    $arr[$daily]['expend'] += $v['money'];
                }
            }
            foreach ($data4 as $k => $v){
                if ($v['time'] >= $startTime && $v['time'] < $endTime){
                    $arr[$daily]['expend'] += $v['gold'];
                }
            }
            $arr[$daily]['profit'] = $arr[$daily]['whole'] - $arr[$daily]['expend']; //盈利
        }
        //统计
        $count['turnover'] = self::where('status', 'neq', 0)->where($where)->sum('money-benefit'); //订单营业额
        $count['recharge'] = UserRecord::sumUserRecord($where2, 'money'); //充值营业额
        $count['whole'] = $count['turnover'] + $count['recharge']; //总营业额
        $count['cash'] = UserCash::sumCash($where2, 'money'); //提现支出
        $count['gold'] = UserGold::sumGold($where, 'gold'); //返现支出
        $count['expend'] = $count['cash'] + $count['gold']; //总支出
        //新增消费 计算今天的营业额
        $toDay = self::where('status', 'neq', 0)->where('time', 'egt', strtotime(date('Y-m-d')))->sum('money-benefit') + UserRecord::sumUserRecord(['status' => 1, 'time' => ['egt', strtotime(date('Y-m-d'))]], 'money');
        return compact('arr', 'count', 'toDay');
    }

    /**
     * 返回首页统计图
     * @param $status
     * @param string $order
     * @return array
     */
    public static function selOrderECharts3($status, $order = 'time asc'){
        $min = self::where('status', 'neq', 0)->min('time');
        $minTime = $min ? strtotime(date('Y-m-d', $min)) : time(); //数据库里面最小的时间
        switch ($status){
            case 1:
                $start = strtotime(date('Y-m-d', strtotime('-1 Month'))); //30内
                break;
            default:
                $start = '';
                break;
        }
        if ($start) {
            $where['time'] = ['egt', $start];
            //如果小于数据库最小时间直接使用数据库最小时间开始组合
            $start = $start < $minTime ? $minTime : $start;
        }else{
            $start = $minTime;
        }
        $day = ceil(((time() - $start) / 86400)); //计算有多少天
        $data = self::where('status', 'neq', 0)->where($where)->field('id, time, money')->order($order)->select();
        $arr = []; //新的数组
        for ($i = 0; $i < $day; $i++){
            $startTime = $start + 86400 * $i; //每天开始时间戳
            $endTime = $start + 86400 * $i + 86400; //每天结束时间戳
            $daily = date('Y-m-d', $startTime); //每天的日期
            $arr[$daily]['toMonthMoney'] = 0; //本月订单金额
            $arr[$daily]['toMonthNum'] = 0; //本月订单数
            foreach ($data as $k => $v) {
                if ($v['time'] >= $startTime && $v['time'] < $endTime) {
                    $arr[$daily]['toMonthMoney'] += $v['money'];
                    $arr[$daily]['toMonthNum'] += 1;
                }
            }
        }
        return $arr;
    }

    /**
     * 返回Excel查询数据
     * @param $status
     * @param string $order
     * @return array
     */
    public static function selOrderExcel($orderStatus, $status, $dateTime, $order = 'time asc'){
        if ($orderStatus) $orderWhere['status'] = $orderStatus - 1;
        $minTime = strtotime(date('Y-m-d', self::where($orderWhere)->min('time'))); //数据库里面最小的时间
        if ($status == 5){
            $dateTime = explode(' - ', $dateTime);
            $start = strtotime($dateTime[0]) < $minTime ? $minTime : strtotime($dateTime[0]);
            $end = strtotime($dateTime[1]) + 86399; //结束时间是日期按当天最后一秒算
            $where['time'] = [['egt', $start], ['elt', $end]];
        }else{
            $start = TimeAssign($status); //开始时间
            if ($start) $where['time'] = ['egt', $start];
        }
        $data = self::where($orderWhere)->where($where)->field('id, order, uid, money, status, time')->order($order)->select();
        $export = [];
        foreach ($data as $k => $v){
            $name = base64_decode(User::getField($v['uid'], 'name'));
            $num = StoreOrderList::countOrderList(['oid' => $v['id']]);
            $statusName = OrderStatus($v['status']);
            $export[] = [
                $v['order'],
                $name,
                $v['money'],
                $num,
                $statusName,
                date('Y-m-d H:i:s', $v['time'])
            ];
        }
        return $export;
    }
}